
from dao.DAOQuanLyNhanVien import DaoQuanLyNhanVien
from datetime import datetime
from google.appengine.api import users
import json as simplejson
from models.GiaBan import GiaBan
from utils.Const import Const
from utils.permission_required import permission_required
import WSGI
import logging
import math
import utils.Const
import webapp2

logger = logging.getLogger("GUIQuanLyNhanVien")

class GuiQuanLyGiaBan(webapp2.RequestHandler):
    priv = ''
    perm = 'HangHoa.QuanLyGiaBan'
    @permission_required
    def get(self):
        lstHangHoa = DaoQuanLyNhanVien.getAllHangHoa()
        lstHangHoaText = ''
        for item in lstHangHoa:
            item['tenHangHoa'] = str(item['id']) + ' - ' + item['tenHangHoa']
            lstHangHoaText += str(item['id']) + ':' + item['tenHangHoa'] + ';'
        
        lstHangHoaText = lstHangHoaText[:-1]
        
        cbbTenNV, _ = DaoQuanLyNhanVien.getListNhanVien('', '', 1000, 0, '')
        for item in cbbTenNV:
            item['tenNV'] = str(item['id']) + ' - ' + item['tenNV']
        
        maNV = ''
        user = users.get_current_user()
        nhanVien = DaoQuanLyNhanVien.getNhanVienByUsername(user.nickname())
        
        if self.priv == 'Staff':
            maNV = nhanVien.key().id().__str__()

        lstKhachHangText = '';
        
        lstKhachHang, _ = DaoQuanLyNhanVien.getListKhachHang(maNV, 10000, 0, maNV)
        for item in lstKhachHang:
            item['tenKhachHang'] = str(item['id']) + ' - ' + item['tenKhachHang']
            lstKhachHangText += str(item['id']) + ':' + item['tenKhachHang'] + ';'
        lstKhachHangText = lstKhachHangText[:-1]
        if maNV == '':
            lstKhachHang = []
        
        nv = DaoQuanLyNhanVien.getNhanVienByUsername(users.get_current_user().nickname())
        lstPerm = DaoQuanLyNhanVien.getListStaffPriviledge(nv.key().id())
        lstMenu = []
        lstNewPerm = []
        for perm in lstPerm:
            lstMenu.append(perm[:perm.index('.')])
            lstNewPerm.append(perm.replace('.', '-'))
        lstMenu = list(set(lstMenu))
        
        template_values = {
                        'lstPerm': lstNewPerm,
                        'lstMenu': lstMenu,
                        'priv': self.priv,
                        'cbbTenNV': cbbTenNV,
                        'lstKhachHang': lstKhachHang,
                        'lstHangHoa': lstHangHoa,
                        'lstHangHoaText': lstHangHoaText,
                        'lstKhachHangText': lstKhachHangText,
                        'nickname': users.get_current_user().nickname(),
                        'signOutUrl': users.create_logout_url(self.request.uri)
        }

        template = WSGI.jinja_environment.get_template('/html/QuanLyGiaBan.html')
        self.response.out.write(template.render(template_values))


class JsonRequestHandler(webapp2.RequestHandler):
    priv = ''
    perm = 'HangHoa.QuanLyGiaBan'
    @permission_required
    def get(self):
        funcName = self.request.get('func')
        funcMapping = {'getListGiaBan': 'getListGiaBan',
                       'updateGiaBan': 'updateGiaBan',
                       'getListKhachHang': 'getListKhachHang'}
        func = getattr(self, funcMapping[funcName]);
        result = func();
        self.response.out.write(result)
    
    def post(self):
        return self.get()
    
    def getListGiaBan(self):
        gridRowNum = int(self.request.get('rows'))
        pageNum = int(self.request.get('page'))
        maKhachHang = self.request.get('maKhachHang')
        maHangHoa = self.request.get('maHangHoa')
        rows, rowNum = DaoQuanLyNhanVien.getListGiaBan(maKhachHang, maHangHoa, gridRowNum, int((pageNum-1)*gridRowNum))
        results = {'page': pageNum, 'total': math.ceil(float(rowNum)/gridRowNum), 'records':rowNum, 'rows':rows}
        return simplejson.dumps(results)
    
    def updateGiaBan(self):
        maGiaBan = self.request.get('id')
        if maGiaBan != '_empty':
            gb = GiaBan.get_by_id(int(maGiaBan))
        else:
            gb = GiaBan()
        oper = self.request.get('oper')
        logger.debug(oper)
        if oper == 'del':
            if self.priv == 'Staff':
                gb.trangThai = utils.Const.TrangThaiGiaBan.XOA
                DaoQuanLyNhanVien.createOrUpdateGiaBan(gb)
            elif self.priv == 'Owner':
                DaoQuanLyNhanVien.deleteGiaBan(gb)
            return 1
        else:
            maHangHoa = int(self.request.get('maHangHoa'))
            hh = DaoQuanLyNhanVien.getHangHoaById(maHangHoa)
            
            gb.maHangHoa = maHangHoa
            gb.tenHangHoa = hh.tenHangHoa
            
            maKhachHang = int(self.request.get('maKhachHang'))
            kh = DaoQuanLyNhanVien.getKhachHangById(maKhachHang)
            
            gb.maKhachHang = maKhachHang
            gb.tenKhachHang = kh.tenKhachHang
            
            giaBan = float(self.request.get('giaBan'))
            gb.giaBan = giaBan
            
            gb.giaMacDinh = hh.giaMacDinh
            
            ngayBatDau = datetime.strptime(self.request.get('ngayBatDau'), '%d/%m/%Y').date()
            
            gb.ngayBatDau = ngayBatDau
            
            if self.priv == 'Staff':
                gb.trangThai = utils.Const.TrangThaiGiaBan.CHUA_DUYET
            elif self.priv == 'Owner':
                gb.trangThai = self.request.get('trangThai')            
            DaoQuanLyNhanVien.createOrUpdateGiaBan(gb)
            return 1
    
    def getListKhachHang(self):
        maNV = self.request.get('maNV')
        lstKH, _ = DaoQuanLyNhanVien.getListKhachHang(maNV, 10000, 0, '')
        for item in lstKH:
            item['tenKhachHang'] = str(item['id']) + ' - ' + item['tenKhachHang'] 
        return simplejson.dumps(lstKH);
        
            
        